#include <stdio.h> 
#include <stdlib.h> 
#include <pthread.h> 
#include <unistd.h> 
#include <string.h> 
 
static pthread_mutex_t mutex; 
static pthread_mutexattr_t attr; 
static pthread_cond_t cond;
static int g_count = 0; 
 
static void *new_thread_start(void) 
{   
    for(;;) {
        pthread_mutex_lock(&mutex); //互斥锁上锁 
        while(0 >= g_count){
            pthread_cond_wait(&cond,&mutex);   //等待条件满足
        }

        while (0 < g_count) {
            g_count--;
        }
        pthread_mutex_unlock(&mutex);//互斥锁解锁 
    }
    pthread_exit(NULL); 
} 

static int loops; 
int main(int argc, char *argv[]) 
{ 
    pthread_t tid1; 
    int ret; 
    
    /* 初始化互斥锁属性对象 */ 
    pthread_mutexattr_init(&attr); 
    pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL);
    /* 初始化互斥锁 */ 
    pthread_mutex_init(&mutex, &attr); 

    /* 初始化条件变量 */
    pthread_cond_init(&cond,NULL);
 
    /* 创建新线程 */ 
    ret = pthread_create(&tid1, NULL, new_thread_start, NULL); 
    if (ret) { 
        fprintf(stderr, "pthread_create error: %s\n", strerror(ret)); 
        exit(-1); 
    } 
 
    for(;;) {
        pthread_mutex_lock(&mutex); //互斥锁上锁 
        g_count++;
        pthread_mutex_unlock(&mutex);//互斥锁解锁
        pthread_cond_signal(&cond);
    }

    /* 销毁互斥锁 及 互斥锁属性对象 */ 
    pthread_mutexattr_destroy(&attr); 
    pthread_mutex_destroy(&mutex);
    /* 销毁条件变量 */
    pthread_cond_destroy(&cond);
 
    exit(0); 
} 
